package com.modakai.med.cmn.listener.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson2.JSON;
import com.modakai.med.cmn.mapper.DictMapper;
import com.modakai.med.vo.DictEeVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

@Slf4j
public class DictRedListener extends AnalysisEventListener<DictEeVo> {

    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;

    /**
     * 缓存的数据
     */
    private List<DictEeVo> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    private DictMapper dictMapper;
    public DictRedListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }


    @Override
    public void invoke(DictEeVo dictEeVo, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}", JSON.toJSONString(dictEeVo));
        // 防止SQL报错
        dictEeVo.setDictCode(StringUtils.isBlank(dictEeVo.getDictCode()) ? "" : dictEeVo.getDictCode());
        cachedDataList.add(dictEeVo);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());
        dictMapper.batchInsert(cachedDataList);
        log.info("存储数据库成功！");
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        log.info("所有数据解析完成！");
    }
}
